package com.loongtech.bi.support;

import com.alibaba.fastjson.JSONArray;
import com.loongtech.bi.action.newsystem.SystemConfig;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class ResponseFilter implements Filter {
	private static final String contentType = "application/json;charset=UTF-8";

    private WebApplicationContext springContext = null;

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain fc) throws IOException, ServletException {
		// 设置返回编码
		/*if(Log.bi.isDebugEnabled()) {
			Log.bi.debug("************* 调用Filter成功设置contentType及跨域信息:" + ((HttpServletRequest) request).getRequestURI() + " *************");
		}*/

        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, HEAD, DELETE");
        httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
        httpServletResponse.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-ACCESS_TOKEN, Access-Control-Allow-Origin, Authorization");
        httpServletResponse.setContentType(contentType);

        SystemConfig systemConfig = (SystemConfig) springContext.getBean("systemConfig");
        String type = systemConfig.getServerType();

        String callback = request.getParameter("callback");

        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession();
        Object userId = session.getAttribute("userId");
        String url = getLastPartURL(req.getRequestURI());
        if ("mid".equals(type) && !url.contains("user/login") && !url.contains("user/ssologin") && !url.contains("user/ssologout") && userId == null) {
            Map<String, Object> jsonMap = new HashMap<>();
            try {
                jsonMap.put("res", "999999");  // 没登录
                jsonMap.put("msg", "login");

                printToJson(httpServletResponse, jsonMap, callback);
            } catch (Exception e) {
                e.printStackTrace();

                jsonMap.put("res", "1");
                jsonMap.put("msg", e.getMessage());

                printToJson(httpServletResponse, jsonMap, callback);
            }

            return;
        }

		fc.doFilter(request, httpServletResponse);
	}

    private static void printToJson(HttpServletResponse response, Map<?, ?> jsonMap, String callback) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/json");
            response.setDateHeader("Expires", 0);
            PrintWriter out = response.getWriter();
            String s = callback == null ? htmlEncode(JSONArray.toJSONString(jsonMap)) : callback + "('"
                    + htmlEncode(JSONArray.toJSONString(jsonMap)) + "')";
            out.println(s);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String htmlEncode(String data) {
        if (data.contains("<")) {
            data = data.replaceAll("<", "&amp;lt;");
        }
        if (data.contains(">")) {
            data = data.replaceAll(">", "&amp;gt;");
        }
        return data;
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        springContext = WebApplicationContextUtils.getWebApplicationContext(arg0.getServletContext());
    }

    private String getLastPartURL(String url){
        if(null == url || url.isEmpty()){
            return url;
        }
        int index0 = url.lastIndexOf("/");
        int index1 = index0>0 ? url.substring(0,index0).lastIndexOf("/") : -1;
        return index1>0? url.substring(index1+1):url;
    }
}
